import os
import re
from collections import Counter
import glob


def process_txt_files():
    # 获取当前路径下所有txt文件
    txt_files = glob.glob("*.txt")
    if not txt_files:
        print("当前路径下没有txt文件")
        return

    for file in txt_files:
        print(f"\n===== 处理文件: {file} =====")

        # 读取文件内容
        try:
            with open(file, 'r', encoding='utf-8') as f:
                content = f.read()
        except Exception as e:
            print(f"读取文件失败: {e}")
            continue

        # 1. 统计字符类型
        total = len(content)
        upper = sum(1 for c in content if c.isupper())  # 大写字母
        lower = sum(1 for c in content if c.islower())  # 小写字母
        digit = sum(1 for c in content if c.isdigit())  # 数字字符
        other = total - upper - lower - digit  # 其他字符

        print("字符统计:")
        print(f"大写字母: {upper}")
        print(f"小写字母: {lower}")
        print(f"数字字符: {digit}")
        print(f"其他字符: {other}")
        print(f"总字符数: {total}")

        # 2. 识别单词及统计频度（单词定义：由字母组成的连续序列，不区分大小写）
        words = re.findall(r'\b[a-zA-Z]+\b', content)  # 匹配纯字母单词
        words_lower = [word.lower() for word in words]  # 统一转为小写统计
        word_freq = Counter(words_lower)

        print("\n单词统计:")
        print(f"单词总数: {len(words)}")
        print("单词频度（前10名，按频次排序）:")
        for word, count in word_freq.most_common(10):  # 显示频次最高的10个单词
            print(f"  {word}: {count}次")

        # 3. 识别段落（段落定义：由空行分隔的内容块）
        paragraphs = re.split(r'\n\s*\n', content.strip())  # 按空行分割
        paragraphs = [p for p in paragraphs if p.strip()]  # 过滤空段落
        print(f"\n段落统计: 共{len(paragraphs)}个段落")

        # 4. 替换"Hello"为"Hi"并保存到新文件
        new_content = content.replace("Hello", "Hi")  # 精确替换"Hello"（区分大小写）
        new_filename = os.path.splitext(file)[0] + "_replaced.txt"

        try:
            with open(new_filename, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"\n替换完成，结果已保存至: {new_filename}")
        except Exception as e:
            print(f"保存替换文件失败: {e}")


if __name__ == "__main__":
    process_txt_files()